package com.duoduo.controller.user;


import com.duoduo.constant.JwtClaimsConstant;
import com.duoduo.dto.UserLoginDTO;
import com.duoduo.entity.User;
import com.duoduo.properties.JwtProperties;
import com.duoduo.result.Result;
import com.duoduo.service.UserService;
import com.duoduo.utils.JwtUtil;
import com.duoduo.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")  // 用户端/用户模块
@Slf4j
@Api(tags = "客户端用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信用户登录
     * @param userLoginDTO：只含前端传来的授权码 code
     * @return UserLoginVO：id，openId，token
     */
    @PostMapping(value ="/login")
    @ApiOperation("微信用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录：{}", userLoginDTO.getCode());

        // 微信登录，得到 User 对象（有openID属性，没有token）
        User user = userService.wxLogin(userLoginDTO);

        // 为微信用户生成jwt令牌 token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());  // 放入用户id到令牌
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(user.getOpenid())
                .build();

        return Result.success(userLoginVO);
    }
}
